ngx.req.set_header('user_id', '')

local ck = require "resty.cookie"
local cookie, err = ck:new()
if not cookie then
    ngx.log(ngx.ERR, err)
    return nil
end

-- get Token cookie
local token, err = cookie:get("user_token")
if not token then
    -- ngx.log(ngx.ERR, err)
    return
end

local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(100)

local ok, err = red:connect(ngx.var.redhost, ngx.var.redport)
if not ok then
    ngx.log(ngx.ERR, "failed to connect to redis: ", err)
    return nil
end

if ngx.var.redauth then
    local ok, err = red:auth(ngx.var.redauth)
    if not ok then
        ngx.log("failed to authenticate: ", err)
        return nil
    end
end

if ngx.var.reddb then
    local ok, err = red:select(ngx.var.reddb)
    if not ok then
        ngx.log("failed to select db: ", ngx.var.reddb, " ", err)
        return nil
    end
end

local userId, err = red:get("CACHE:USER:TOKEN:" .. token)
if not userId then
    return
end

if userId == ngx.null then
    return
end

ngx.log(ngx.ERR, userId)

ngx.req.set_header('user_id', userId)


local ok, err = red:set_keepalive(10000, 100)
if not ok then
    ngx.say("failed to set keepalive: ", err)
    return
end